<?php
namespace Agent\Controller;

use Utuo\BackgroundController;
use Agent\Model\DistributionShopOrderModel;
use Agent\Model\DistributionShopRateModel;
use My\Model\ProductRateModel;

class DistributionShopSubAgentOrderController extends BackgroundController {
	
	private $deliverMethod = array(
		'0' => '物流',
		'1' => '无需配送',
	);
	
	/* 订单类型 */
	protected $orderTypes = array(
	    0 => '待发货',
	    1 => '交易成功',
	    3 => '待买家签收',
	    4 => '待卖家审核评价',
	    5 => '待买家付款',
	    7 => '已支付订单',
	    6 => '退款订单',
	    2 => '全部',
	);
	
	public function _initialize() {
		$this->setControllerTitle("订单管理");
		$this->setActionTitle(array(
			'index' => '订单列表',
			'deliver' => '发货',
			'detials' => '订单详细',
			'comment' => '评价',
		));
		$this->setActionNav("index");
	}
	
	/**
	 * array(
	 * 	 'type' // 类型 *
	 * )
	 * @return Ambigous <number, mixed>
	 */
	public function getParams() {
	    $type = I("type", 0);
	    $agentId = I("agentId", $this->aid, "intval");
	    $showSubOrder = I("showSubOrder", 0);
	    $agentName = I("agentName", "");
	    /* 类型(*) */
	    if ( !in_array( $type, array_keys( $this->orderTypes ) ) ) {
	        $type = 2;
	    }
	    $params['type'] = $type;
	    $params['agentId'] = $agentId;
	    $params['agentName'] = $agentName;
	    $params['showSubOrder'] = $showSubOrder;
	    return $params;
	}
	
	public function getCondition( $params ) {
	    $type = $params['type'];
	    $agentId = $params['agentId'];
	    $condition = array(
	        'agent_id' => $agentId, // 直属订单
	    );
	    /* 类型 */
	    if($type == 0) { // 待发货
	        $condition['order_status'] = DistributionShopOrderModel::ORDER_STATUS_SHIPPING;
	    } elseif ($type == 1) { // 交易成功
	        $condition ['order_status'] = DistributionShopOrderModel::ORDER_STATUS_COMPLETED;
	    }elseif($type == 3){ // 待买家签收
	        $condition ['order_status'] = DistributionShopOrderModel::ORDER_STATUS_SIGN;
	    }elseif($type == 4){ // 待卖家完成评价
	        $condition ['order_status'] = DistributionShopOrderModel::ORDER_STATUS_COMPLETED;
	        $condition ['rate_status'] = array('in', array(DistributionShopRateModel::RATE_STATUS_BUYER, DistributionShopRateModel::RATE_STATUS_UNRATE)) ;
	    }elseif($type == 2){} // 全部
	    
	    /*跨级显示*/
	    if ( $params['showSubOrder'] ) {
	        $parentIds = array($agentId);
	        $tmp = array($agentId);
	        while($parentIds and !!$alist = M("Agent")->where(array("parent_id"=>array("in", $tmp)))->select()) {
	            $tmp = array();
	            foreach ( $alist as $v ) {
	                $tmp[] = $parentIds[] = $v["id"];
	            }
	        }
	        $condition['agent_id'] = array("in", $parentIds);
	    }
	    return $condition;
	}
	
	public function indexAction() {
		$this->setActionLink();
		$type = I("type", 0);
		$d = D("DistributionShopOrder");
		$params = $this->getParams();
		$condition = $this->getCondition($params);
		$productOrderLists = $d->where($condition)->limit($this->getPageSize())->page($this->getPage())->order("id desc")->select();
		$productOrderCount = $d->where($condition)->count();
		foreach ($productOrderLists as &$v) {
			$v["orderShowStatus"] = $d->getOrderShowStatus($v['order_status'], $v['pay_status']);
			$this->getOperate($v);
		}
		$this->showPage($productOrderCount, $this->getPageSize(), $params);
		/* 代理树 */
		$agentList = array(array("pId"=>0, "id"=>$this->aid, "name"=>"当前代理"));
		$parentIds = array($this->aid);
		while($parentIds and !!$alist = M("Agent")->where(array("parent_id"=>array("in", $parentIds)))->select()) {
		    $parentIds = array();
		    foreach ( $alist as $v ) {
		        $parentIds[] = $v["id"];
		        array_push($agentList, array("id" => $v["id"], "pId"=> $v["parent_id"]*1, "name"=>$v["name"]."（".($v["level"]+1)."级代理商）"));
		    }
		}
		$this->assign("agentJson", json_encode($agentList));
		$this->assign("orderTypesOptions", $this->getOption($this->orderTypes, $params['type']));
		$this->assign("params", $params);
		$this->assign("productOrderLists", $productOrderLists);
		$this->display();
	}
	
	// 发货
	public function deliverAction() {
		$d = D("DistributionShopOrder");
		$orderId = I("id", 0);
		$productOrder = $d->where(array(
							'agent_id' => $this->aid,
							'id' => $orderId,
						))->find();
		$this->assign("productOrder", $productOrder);
		$this->display();
	}
	
	// 发货提交
	public function deliverPostAction() {
		$d = D("DistributionShopOrder");
		$orderId = I("id", 0, "intval");
		// 验证
		$order = $d->where(array( "agent_id" => $this->aid, "id" => $orderId))->find();
		$order or $this->ajaxError("订单不存在");
		$order['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SIGN and $this->ajaxError("订单已发货");
		$d->field('deliver_method,express_name,shipping_no,deliverman_uid')->create();
		$data = array(
				'order_status' => DistributionShopOrderModel::ORDER_STATUS_SIGN,
				'shipping_time' => time(), );
		if( $d->deliver_method == 0 ) {
			$data['express_name'] = $d->express_name or $this->ajaxError("请选择快递名称.");
			$data['shipping_no'] = $d->shipping_no or $this->ajaxError("请填写物流单号.");
		} elseif( $d->deliver_method == 1 ) {
			// 无需配送
		} else {
			$this->ajaxError("没有您选择的配送方式");
		}
		$data['deliver_method'] = $d->deliver_method;
		// 更新产品销量
		$productSalesSummary = M("DistributionShopOrderGoods")->where(array(
									"order_id" => $orderId
								))->group("product_id")->field("product_id,sum(product_number) as totalName")->select();
		foreach ($productSalesSummary as $v) {
			M("DistributionShopGoods")->where("id=%d", $v['product_id'])->setInc("saled_count", $v['totalName']);
		}
		// 设置发货状态
		false !== $d->where(array( 'id' => $orderId, ))->save($data) and $this->ajaxSuccess("发货成功");
		$this->ajaxSuccess("发货失败");
	}
	
	// 订单评论
	public function commentAction() {
		$orderId = I('id');
		$productOrder = D( "DistributionShopOrder" )->getOrder($orderId, 0, $this->aid);
		//$this->bindComment($productOrder);
		$this->assign("productOrder", $productOrder);
		$this->display();
	}
	
	// 绑定评价内容
	public function bindComment( &$productOrder ) {
		$productRateLists = M("ProductRate")->where(array('order_id' => $productOrder['id'], 'reviewer' => ProductRateModel::REVIEWER_BUYER))->select();
		foreach ( $productOrder['orderItems'] as $productId => &$v ) {
			foreach ( $v['items'] as $k => &$item ) {
				foreach ( $productRateLists as $rate) {
					if ( $rate['product_id']==$productId and $rate['order_goods_id']==$item['orderGoodsId'] ) {
						$item['buyer_rate_content'] = $rate['content'];
						$item['buyer_rate_time'] = $rate['create_time'];
						break;
					}
				}
			}
		}
	}
	
	/**
	 * 卖家评价提交
	 *   格式:
	 * 		'order_id' => '订单id',
	 * 		'rates' => array('order_goods_id(订单商品编号)' => array(
	 *						 'content' => '评价内容',
	 *						),... ...);
	 
	public function commentPostAction() {
		$orderId = I('id') or $this->ajaxError('未知订单号');
		$rates = I('rates', array()) or $this->ajaxError('评论内容不能为空');
		$order =  D( "ProductOrder" )->getOrder($orderId, 0, $this->aid)  or $this->ajaxError("未找到订单");
		false === D("ProductRate")->submitRate($order, $rates, $this->aid, ProductRateModel::REVIEWER_SALLER) and $this->ajaxSuccess("评价失败");
		$this->ajaxSuccess("评价成功");
	}*/
	
	
	
	/**
	 * 订单详细
	 */
	public function detialsAction() {
		$orderId = I("id", 0);
		$order = $this->getOrder($orderId);
		if ( $order['operate'] == 'deliver') {
			$express = \Utuo\Express::getInstance();
			$expressNames = $express->getExpressname();
			$expressValues = array_values($expressNames);
			$order['deliverMethodRadio'] = $this->getRadio("deliver_method", $this->deliverMethod, '0');
			$order['expressOptions'] = $this->getOption(array_combine($expressValues, $expressValues), $order['express_name'], "====请选择快递====");
		}
		$this->assign("order", $order);
		$this->display();
	}
	
	private function setActionLink() {
		$types = array(
			0 => "待发货",
			3 => "待买家签收",
			1 => "交易成功",
			4 => "待卖家完成评价",
			2 => "全部"
		);
		foreach ($types as $k => $v) {
			$this->setLinkNav("$v", U(CONTROLLER_NAME.'/index', array('type'=>$k)));
		}
	}
	
	// 获得订单操作
	private function getOperate(&$v) {
		if(($v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_SHIPPING)) $v['operate'] = "deliver";
		if($v['order_status'] == DistributionShopOrderModel::ORDER_STATUS_COMPLETED and in_array($v['rate_status'], array(DistributionShopRateModel::RATE_STATUS_BUYER))) {
			$v['operate'] = "check_comment";
		}
	}
	
	/**
	 * 获得一个订单
	 * @param unknown $id
	 * @return Ambigous <\Think\mixed, boolean, NULL, multitype:, unknown, mixed, string, object>
	 */
	private function getOrder($id) {
		$order = M ( "DistributionShopOrder orders" )->join( "__WECHAT_USER__ user on orders.uid=user.id", "LEFT")->join ( "__CN_PROVINCE__ province on orders.province = province.code", "LEFT" )->join ( "__CN_CITY__ city on orders.city = city.code", "LEFT" )->join ( "__CN_AREA__ area on orders.area = area.code", "LEFT" )->field ( "orders.*,user.nickname as userName,province.name as provinceName, city.name as cityName, area.name as areaName" )->where ( "orders.id=%d", $id )->find ();
		if ( !$order ) return null;
		$orders = array (
				&$order
		);
		$this->bindOrderDetail ( $orders );
		return $order;
	}
	
	/* 绑定订单详细 */
	private function bindOrderDetail(&$orderLists) {
		/* 关联订单商品 */
		$dProductOrder = D ( "Agent/DistributionShopOrder" );
		$mProductGoods = M ( "DistributionShopOrderGoods" );
		foreach ( $orderLists as &$v ) {
			// 绑定显示状态
			$v ["orderStatusName"] = $dProductOrder->getOrderShowStatus ( $v ['order_status'], $v ['pay_status'], $v ['shipping_status'] );
			// 获得操作
			$this->getOperate($v);
			// 绑定订单商品
			$orderGoods = $mProductGoods->where ( "order_id=%d", $v ['id'] )->select ();
			foreach ( $orderGoods as &$v0 ) {
				$v ['orderItems'] [$v0 ['product_id']] or $v ['orderItems'] [$v0 ['product_id']] = array (
						'productId' => $v0 ['product_id'],
						'productName' => $v0 ['product_name'],
						'items' => array ()
				);
				$v ['orderItems'] [$v0 ['product_id']] ['items'] [] = array (
						'productPic' => $v0 ['product_pic'],
						'productNumber' => $v0 ['product_number'],
						'productPrice' => $v0 ['product_price'],
						'productAttr' => $v0 ['product_attr']
				);
			}
		}
	}
	
}
